package com.ruicar.afs.cloud.workflow.greatwall.processor.impl.objcode;

import com.alibaba.fastjson.TypeReference;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.dynamicrequest.DynamicRequest;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.workflow.api.dto.afsprocess.response.FlowExceptionResponse;
import com.ruicar.afs.cloud.workflow.greatwall.dto.GwtRequest;
import com.ruicar.afs.cloud.workflow.greatwall.entity.AfsGreatWallWorkflowMappingInfo;
import com.ruicar.afs.cloud.workflow.greatwall.enums.GwtMsgType;
import com.ruicar.afs.cloud.workflow.greatwall.enums.GwtObjectCode;
import com.ruicar.afs.cloud.workflow.greatwall.enums.RequestPath;
import com.ruicar.afs.cloud.workflow.greatwall.service.AfsGreatWallWorkflowBizDataService;
import com.ruicar.afs.cloud.workflow.greatwall.service.AfsGreatWallWorkflowMappingInfoService;
import com.ruicar.afs.cloud.workflow.greatwall.service.AfsGreatWallWorkflowNoticeExceptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;

@Component
@Slf4j
public class FlowDefaultErrorProcessor extends AbsFlowErrorNoticeProcessor{


    /**
     * Dynamic request
     * <p>Description: </p>
     */
    private final DynamicRequest dynamicRequest;

    public FlowDefaultErrorProcessor(AfsGreatWallWorkflowBizDataService afsGreatWallWorkflowBizDataService, AfsGreatWallWorkflowNoticeExceptionService afsGreatWallWorkflowNoticeExceptionService, AfsGreatWallWorkflowMappingInfoService afsGreatWallWorkflowMappingInfoService, DynamicRequest dynamicRequest) {
        super(afsGreatWallWorkflowBizDataService, afsGreatWallWorkflowNoticeExceptionService, afsGreatWallWorkflowMappingInfoService);
        this.dynamicRequest = dynamicRequest;
    }

    @Override
    public GwtMsgType belongMsg() {
        return GwtMsgType.FLOW_EXCEPTION_NOTICE;
    }

    @Override
    public GwtObjectCode objectCode() {
        return GwtObjectCode.FLOW_DEFAULT_ERROR;
    }

    @Override
    public String processKey() {
        return MessageFormat.format("{0}-{1}", AfsEnumUtil.key(belongMsg()), AfsEnumUtil.key(objectCode()));
    }

    boolean noticeBiz(GwtRequest request, AfsGreatWallWorkflowMappingInfo afsGreatWallWorkflowMappingInfo) {
        try {
            IResponse<FlowExceptionResponse> response =
                    dynamicRequest.post(afsGreatWallWorkflowMappingInfo.getServiceName(), AfsEnumUtil.key(RequestPath.FLOW_DEFAULT_ERROR), getRequest(request,afsGreatWallWorkflowMappingInfo), new TypeReference<FlowExceptionResponse>() {
                    });
            return CommonConstants.SUCCESS.equalsIgnoreCase(response.getCode()) && response.getData().isSuccess();
        } catch (Exception e) {
            log.error("", e);
            throw e;
        }
    }
}
